<template>
  <el-form :model="form" ref="form" :rules="rules" class="form">
    <el-form-item class="form-item" prop="username">
      <!-- 2.1@focus="clearRules('username')" -->
      <el-input placeholder="用户名/手机" v-model="form.username" @focus="clearRules('username')"></el-input>
    </el-form-item>

    <el-form-item class="form-item" prop="password">
      <el-input
        placeholder="密码"
        type="password"
        v-model="form.password "
        @focus="clearRules('password')"
      ></el-input>
    </el-form-item>

    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>

    <el-button class="submit" type="primary" @click="handleLoginSubmit">登录</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      form: {
        username: "13800138000",
        password: "123456",
      },
      // 表单规则
      rules: {
        //要求的表单数据规则
        username: [
          //required: true为是否必填,首先判断,每一个{}代表每一个规则
          //required 是否必填, message 消息提示, trigger 触发事件类型
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 6, message: "长度必须六位数", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleLoginSubmit() {
      //发送前的一次保底总校验,希望无需触发器, 也想将整个表单全部验证一次
      this.$refs.form.validate((isrules, mistake) => {
        if (isrules) {
          // 希望将登陆这个异步请求,传this.form过去
          this.$store.dispatch("user/login", this.form).then((res) => {
            // 成功提示
            this.$message({
              message: "登录成功",
              type: "success",
              duration: 800,
            });
            // 跳转到首页
            setTimeout(() => {
              if (this.$route.path == "/user/login") {
                this.$router.replace("/");
              }
            }, 1000);
          });
        } else {
          console.log(mistake);
        }
      });
    },
    //2.2输入框聚焦时, 暂时清楚错误提示,clearValidate移除表单项的校验结果
    clearRules(propinfo) {
      this.$refs.form.clearValidate(propinfo);
    },
  },
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>
